package org.zhaya.sdk.processors;

import com.google.common.collect.Lists;
import io.logz.sawmill.Doc;
import io.logz.sawmill.ProcessResult;
import io.logz.sawmill.Processor;
import io.logz.sawmill.annotations.ProcessorProvider;
import io.logz.sawmill.exceptions.ProcessorConfigurationException;
import io.logz.sawmill.utilities.JsonUtils;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.apache.commons.collections4.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Author gleen
 * @Date 2022/11/22 12:07
 */
@ProcessorProvider(
        type = "upperCase",
        factory = UpperCaseProcessor.Factory.class
)
public class UpperCaseProcessor implements Processor {
    private final List<String> fields;

    public UpperCaseProcessor(List<String> fields) {
        this.fields = Objects.requireNonNull(fields, "fields cannot be null");
    }

    @Override
    public ProcessResult process(Doc doc) {
        List<String> missingFields = Lists.newArrayList();

        for (String field : this.fields) {
            if (!doc.hasField(field, String.class)) {
                missingFields.add(field);
            } else {
                String value = doc.getField(field);
                doc.addField(field, value.toUpperCase());
            }
        }

        if (CollectionUtils.isNotEmpty(missingFields)) {
            return ProcessResult.failure(String.format("failed to uppercase fields in path [%s], fields are missing or not instance of [%s]", missingFields, String.class));
        } else {
            return ProcessResult.success();
        }
    }

    @Getter
    @Setter
    @NoArgsConstructor
    public static class Configuration implements Processor.Configuration {
        private List<String> fields;

    }

    @NoArgsConstructor
    public static class Factory implements Processor.Factory {

        @Override
        public UpperCaseProcessor create(Map<String, Object> config) {
            Configuration upperCaseConfig = JsonUtils.fromJsonMap(Configuration.class, config);
            if (CollectionUtils.isEmpty(upperCaseConfig.getFields())) {
                throw new ProcessorConfigurationException("failed to parse upperCase processor config, could not resolve fields");
            } else {
                return new UpperCaseProcessor(upperCaseConfig.getFields());
            }
        }
    }
}
